import * as XLSX from 'xlsx'
export class XLSXUtil {
  static getSourceData(file: any, cb: (params: { dataSource: any[]; columns: any[] }) => void) {
    const reader = new FileReader()
    // 处理文件内容
    reader.onload = (e: any) => {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })

      const worksheet = workbook.Sheets[workbook.SheetNames[0]]
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as any[]
      // 提前文件内容
      const _headers: string[] = jsonData[0]
      const _rows = jsonData
        .slice(1)
        .filter((v) => v.length)
        .map((row: any, index: number) => {
          const _row: Record<string, any> = {}
          _headers.forEach((header: string, hIndex: number) => {
            _row[header] = row[hIndex]
          })
          return {
            index: index + 1,
            ..._row
          }
        })
      const columns = _headers.map((v) => ({
        title: v,
        dataIndex: v,
        key: v
      }))

      cb({
        dataSource: _rows,
        columns
      })
    }
    // 读取文件内容
    reader.readAsArrayBuffer(file)
    // reader.readAsBinaryString(file)
  }
}
